
// ContentView.swift
// SportStream
// Created on March 23, 2025

import SwiftUI
import MobileVLCKit

// هيكل القناة مع توافق Vavoo والقنوات الرياضية
struct Channel: Identifiable, Codable {
    let id: String
    let name: String
    let displayName: String
    let group: String
    let logo: String
    let path: String?
    var isFavorite: Bool = false // لدعم المفضلة
}

// إدارة القنوات مع جلب البيانات من Vavoo أو Joker Apps
class ChannelLinkManager: ObservableObject {
    @Published var channels: [Channel]
    private let vavooCache = NSCache<NSString, NSString>() // التخزين المؤقت لروابط Vavoo فقط
    
    init(channels: [Channel]) {
        self.channels = channels
        vavooCache.countLimit = 100 // حد أقصى للتخزين
    }
    
    func fetchStreamUrl(for channel: Channel) async -> String? {
        if channel.group == "القنوات الرياضية" {
            if channel.path != nil { // القنوات الأساسية من Joker
                return await fetchSportsStreamUrl(channelPath: channel.path!)
            } else { // القنوات الاحتياطية من Vavoo
                let key = channel.id as NSString
                if let cachedUrl = vavooCache.object(forKey: key) {
                    return cachedUrl as String
                }
                if let url = await fetchVavooStreamUrl(channelId: channel.id) {
                    vavooCache.setObject(url as NSString, forKey: key)
                    return url
                }
                return nil
            }
        } else {
            let key = channel.id as NSString
            if let cachedUrl = vavooCache.object(forKey: key) {
                return cachedUrl as String
            }
            if let url = await fetchVavooStreamUrl(channelId: channel.id) {
                vavooCache.setObject(url as NSString, forKey: key)
                return url
            }
            return nil
        }
    }
    
    private func fetchSportsStreamUrl(channelPath: String) async -> String? {
        let urlString = "http://joker-apps.com/play/\(channelPath)"
        guard let url = URL(string: urlString) else {
            print("رابط غير صالح: \(urlString)")
            return nil
        }
        
        var request = URLRequest(url: url)
        request.setValue("joker-apps.com:443", forHTTPHeaderField: "Host")
        request.setValue("*/*", forHTTPHeaderField: "Accept")
        request.setValue(Locale.current.identifier, forHTTPHeaderField: "Accept-Language")
        request.setValue(getUserAgent(), forHTTPHeaderField: "User-Agent")
        request.setValue("bytes=0-", forHTTPHeaderField: "Range")
        request.timeoutInterval = 3
        
        let sessionConfig = URLSessionConfiguration.default
        sessionConfig.timeoutIntervalForRequest = 3
        sessionConfig.timeoutIntervalForResource = 5
        sessionConfig.requestCachePolicy = .reloadIgnoringLocalCacheData
        let session = URLSession(configuration: sessionConfig, delegate: RedirectHandler(), delegateQueue: nil)
        
        do {
            let (_, response) = try await session.data(for: request)
            guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 302,
                  let location = httpResponse.value(forHTTPHeaderField: "Location") else {
                print("لم يتم العثور على إعادة توجيه أو حقل Location")
                return nil
            }
            return location.trimmingCharacters(in: .whitespacesAndNewlines)
        } catch {
            print("خطأ في جلب رابط البث الرياضي: \(error)")
            return nil
        }
    }
    
    private func fetchVavooStreamUrl(channelId: String) async -> String? {
        let url = generateChannelUrl(channelId: channelId)
        let requestUrl = URL(string: "https://vavoo.to/vto-cluster/mediahubmx-resolve.json")!
        var request = URLRequest(url: requestUrl, timeoutInterval: 3.0)
        request.httpMethod = "POST"
        request.setValue("vavoo.to", forHTTPHeaderField: "Host")
        request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
        request.setValue("Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.0 Mobile/15E148 Safari/604.1", forHTTPHeaderField: "User-Agent")
        request.setValue("eyJkYXRhIjoie1wiYXBwXCI6e319Iiwic2lnbmF0dXJlIjoiIn0=", forHTTPHeaderField: "MediaHubMX-Signature")
        
        let jsonData: [String: Any] = ["language": "AA", "region": "AA", "url": url, "clientVersion": "3.0.2"]
        
        do {
            request.httpBody = try JSONSerialization.data(withJSONObject: jsonData)
            let configuration = URLSessionConfiguration.default
            configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
            configuration.urlCache = nil
            let session = URLSession(configuration: configuration)
            let (data, response) = try await session.data(for: request)
            
            guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else {
                print("استجابة غير صالحة لـ \(url): \(response)")
                return nil
            }
            
            if let jsonArray = try JSONSerialization.jsonObject(with: data) as? [[String: String]],
               let streamUrl = jsonArray.first?["url"] {
                return streamUrl
            }
        } catch {
            print("خطأ في جلب رابط البث من Vavoo: \(error)")
        }
        return nil
    }
    
    private func generateRandomValue() -> String {
        let characters = "abcdef0123456789"
        return String((0..<12).map { _ in characters.randomElement()! })
    }
    
    private func generateChannelUrl(channelId: String) -> String {
        let randomValue = generateRandomValue()
        return "https://vavoo.to/vto-tv/play/\(channelId)\(randomValue)"
    }
    
    private func getUserAgent() -> String {
        let device = UIDevice.current
        let systemName = device.systemName
        let systemVersion = device.systemVersion
        let model = device.model
        let identifier = Bundle.main.bundleIdentifier ?? "com.Ahmed-aldeab.SportStream"
        return "CFNetwork/1410.1 Darwin/22.6.0 (\(model) \(systemName)/\(systemVersion)) \(identifier)"
    }
    
    func toggleFavorite(channelId: String) {
        if let index = channels.firstIndex(where: { $0.id == channelId }) {
            channels[index].isFavorite.toggle()
            saveFavorites()
        }
    }
    
    private func saveFavorites() {
        let encoder = JSONEncoder()
        if let encoded = try? encoder.encode(channels.filter { $0.isFavorite }) {
            UserDefaults.standard.set(encoded, forKey: "favoriteChannels")
        }
    }
    
    func loadFavorites() {
        if let data = UserDefaults.standard.data(forKey: "favoriteChannels"),
           let favorites = try? JSONDecoder().decode([Channel].self, from: data) {
            for favorite in favorites {
                if let index = channels.firstIndex(where: { $0.id == favorite.id }) {
                    channels[index].isFavorite = true
                }
            }
        }
    }
}

// إدارة المشغل VLC
class PlayerManager: ObservableObject {
    static let shared = PlayerManager()
    @Published private var mediaPlayer: VLCMediaPlayer = VLCMediaPlayer()
    @Published var showControls = false
    
    private init() {
        mediaPlayer.videoAspectRatio = UnsafeMutablePointer<Int8>(mutating: ("16:9" as NSString).utf8String)
        mediaPlayer.scaleFactor = 0
    }
    
    func play(url: String) {
        killPlayer()
        guard let mediaURL = URL(string: url) else {
            print("رابط غير صالح: \(url)")
            return
        }
        let media = VLCMedia(url: mediaURL)
        mediaPlayer.media = media
        mediaPlayer.play()
        print("بدأ تشغيل البث: \(url)")
    }
    
    func pause() {
        mediaPlayer.pause()
    }
    
    func stop() {
        mediaPlayer.stop()
    }
    
    func retry(url: String) {
        stop()
        play(url: url)
    }
    
    func killPlayer() {
        mediaPlayer.stop()
        mediaPlayer.media = nil
        mediaPlayer.drawable = nil
    }
    
    func setDrawable(_ view: UIView) {
        mediaPlayer.drawable = view
    }
    
    func loadSubtitles(url: URL) {
        mediaPlayer.addPlaybackSlave(url, type: .subtitle, enforce: true)
    }
    
    func getMediaPlayer() -> VLCMediaPlayer {
        return mediaPlayer
    }
}

// عرض المشغل VLC
struct VLCMediaPlayerView: UIViewRepresentable {
    @ObservedObject var manager: PlayerManager
    let streamURL: String
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    func makeUIView(context: Context) -> UIView {
        let playerView = UIView()
        manager.setDrawable(playerView)
        manager.play(url: streamURL)
        return playerView
    }
    
    func updateUIView(_ uiView: UIView, context: Context) {
        if manager.getMediaPlayer().drawable == nil {
            manager.setDrawable(uiView)
        }
    }
    
    func dismantleUIView(_ uiView: UIView, coordinator: Coordinator) {
        manager.killPlayer()
    }
    
    class Coordinator: NSObject, VLCMediaPlayerDelegate {
        var parent: VLCMediaPlayerView
        
        init(_ parent: VLCMediaPlayerView) {
            self.parent = parent
        }
        
        func mediaPlayerStateChanged(_ aNotification: Notification!) {
            let state = parent.manager.getMediaPlayer().state
            if state == .error {
                print("خطأ في تشغيل البث")
            } else if state == .playing {
                print("البث يعمل بشكل صحيح")
            }
        }
    }
}

// شاشة التشغيل مع تحسينات
struct PlayerScreen: View {
    let channel: Channel
    @Binding var showPlayerScreen: Bool
    @Binding var showGroupScreen: Bool
    @StateObject private var playerManager = PlayerManager.shared
    @EnvironmentObject var linkManager: ChannelLinkManager
    @State private var streamURL: String? = nil
    @State private var isLoading = true
    @State private var loadingProgress: Double = 0.0
    @State private var errorMessage: String? = nil
    @State private var isFullScreen = false
    
    var body: some View {
        GeometryReader { geometry in
            ZStack {
                AsyncImage(url: URL(string: channel.group == "القنوات الرياضية" ? "https://example.com/sports-bg.jpg" : "https://example.com/news-bg.jpg")) { image in
                    image.resizable().scaledToFill()
                } placeholder: { Color.black }
                .edgesIgnoringSafeArea(.all)
                
                VStack(spacing: 0) {
                    if !isFullScreen {
                        HStack {
                            Image(channel.logo)
                                .resizable()
                                .scaledToFit()
                                .frame(width: 50, height: 50)
                                .clipShape(Circle())
                                .shadow(color: .blue.opacity(0.7), radius: 10)
                            Text(channel.displayName)
                                .font(.custom("Questv1-Bold", size: 20))
                                .foregroundColor(.white)
                            Spacer()
                            Button(action: {
                                playerManager.pause()
                                withAnimation(.easeInOut(duration: 0.3)) {
                                    showPlayerScreen = false
                                    showGroupScreen = true
                                }
                            }) {
                                Image(systemName: "xmark")
                                    .foregroundColor(.white)
                                    .padding(10)
                                    .background(Color.black.opacity(0.7))
                                    .clipShape(Circle())
                            }
                        }
                        .padding(.horizontal, 15)
                        .padding(.top, geometry.safeAreaInsets.top + 10)
                    }
                    
                    ZStack {
                        if isLoading {
                            ZStack {
                                Color.black.opacity(0.8)
                                VStack(spacing: 15) {
                                    ProgressView(value: loadingProgress, total: 1.0)
                                        .progressViewStyle(LinearProgressViewStyle(tint: .blue))
                                        .frame(width: 200)
                                    Text(LocalizedStringKey("loading"))
                                        .font(.custom("Questv1-Bold", size: 16))
                                        .foregroundColor(.white)
                                }
                            }
                        } else if let url = streamURL {
                            VLCMediaPlayerView(manager: playerManager, streamURL: url)
                                .frame(maxWidth: .infinity, maxHeight: isFullScreen ? .infinity : geometry.size.height * (UIDevice.current.orientation.isLandscape ? 1.0 : 0.6))
                                .overlay(
                                    PlayerControlsView(manager: playerManager, isFullScreen: $isFullScreen, streamURL: url)
                                        .opacity(playerManager.showControls ? 1 : 0)
                                )
                                .gesture(
                                    TapGesture()
                                        .onEnded {
                                            withAnimation(.spring()) {
                                                playerManager.showControls.toggle()
                                            }
                                        }
                                )
                        } else if let error = errorMessage {
                            Text(error)
                                .font(.custom("Questv1-Bold", size: 16))
                                .foregroundColor(.red)
                        }
                    }
                    .frame(maxHeight: .infinity)
                }
            }
            .onAppear {
                Task {
                    withAnimation(.linear(duration: 3)) {
                        loadingProgress = 0.7
                    }
                    await loadStream()
                }
            }
            .onDisappear {
                playerManager.killPlayer()
            }
            .transition(.scale.combined(with: .opacity))
        }
        .environment(\.layoutDirection, .rightToLeft)
        .statusBar(hidden: isFullScreen)
    }
    
    private func loadStream() async {
        isLoading = true
        if let url = await linkManager.fetchStreamUrl(for: channel) {
            streamURL = url
            errorMessage = nil
            playerManager.play(url: url)
        } else {
            errorMessage = "فشل جلب رابط البث"
        }
        isLoading = false
        loadingProgress = 1.0
    }
}

// واجهة التحكم المحسنة
struct PlayerControlsView: View {
    @ObservedObject var manager: PlayerManager
    @Binding var isFullScreen: Bool
    let streamURL: String
    
    var body: some View {
        VStack {
            Spacer()
            HStack(spacing: 50) {
                Spacer()
                
                Button(action: {
                    if let url = manager.getMediaPlayer().media?.url?.absoluteString {
                        manager.play(url: url)
                    }
                    withAnimation { manager.showControls = false }
                }) {
                    Image(systemName: "play.fill")
                        .font(.system(size: 24))
                        .foregroundColor(.white)
                }
                .accessibilityLabel("تشغيل")
                
                Button(action: {
                    manager.pause()
                    withAnimation { manager.showControls = true }
                }) {
                    Image(systemName: "pause.fill")
                        .font(.system(size: 24))
                        .foregroundColor(.white)
                }
                .accessibilityLabel("إيقاف مؤقت")
                
                Button(action: {
                    manager.stop()
                    withAnimation { manager.showControls = true }
                }) {
                    Image(systemName: "stop.fill")
                        .font(.system(size: 24))
                        .foregroundColor(.white)
                }
                .accessibilityLabel("إيقاف")
                
                Button(action: {
                    manager.retry(url: streamURL)
                }) {
                    Image(systemName: "arrow.clockwise")
                        .font(.system(size: 24))
                        .foregroundColor(.white)
                }
                .accessibilityLabel("إعادة المحاولة")
                
                Button(action: {
                    manager.loadSubtitles(url: URL(string: "https://example.com/subtitles.srt")!) // رابط افتراضي
                }) {
                    Image(systemName: "captions.bubble.fill")
                        .font(.system(size: 24))
                        .foregroundColor(.white)
                }
                .accessibilityLabel("إضافة ترجمة")
                
                Button(action: {
                    withAnimation(.easeInOut(duration: 0.3)) {
                        isFullScreen.toggle()
                    }
                }) {
                    Image(systemName: isFullScreen ? "arrow.down.right.and.arrow.up.left" : "arrow.up.left.and.arrow.down.right")
                        .font(.system(size: 24))
                        .foregroundColor(.white)
                }
                .accessibilityLabel("تغيير وضع الشاشة")
                
                Spacer()
            }
            .padding(.bottom, 20)
            .background(
                LinearGradient(
                    gradient: Gradient(colors: [Color.black.opacity(0), Color.black.opacity(0.8)]),
                    startPoint: .top,
                    endPoint: .bottom
                )
            )
        }
        .transition(.opacity)
    }
}

// الشاشة الرئيسية
struct MainView: View {
    @StateObject private var linkManager: ChannelLinkManager
    @State private var statusText = "اختر قناتك المفضلة"
    @State private var selectedGroup: String?
    @State private var currentTab: Tab = .home
    @State private var showPlayerScreen = false
    @State private var showGroupScreen = false
    @State private var selectedChannel: Channel?
    
    init() {
        let initialChannels: [Channel] = [
            // القنوات الرياضية (الأساسية من Joker، الاحتياطية من Vavoo)
            Channel(id: "679604721", name: "beIN Sport 1 HD", displayName: "beIN Sport 1 HD", group: "القنوات الرياضية", logo: "beinSports_01_logo", path: "PhEJBHxb2ZwxlnzGwrQezD_q-Wd1BhdOoCtqcr2VRl0/ts"),
            Channel(id: "1564627444", name: "beIN Sport 1 HD (Backup)", displayName: "beIN Sport 1 (Backup)", group: "القنوات الرياضية", logo: "beinSports_01_logo", path: nil),
            Channel(id: "1730092216", name: "beIN Sport 2 HD", displayName: "beIN Sport 2 HD", group: "القنوات الرياضية", logo: "beinSports_02_logo", path: "PhEJBHxb2ZwxlnzGwrQezDhTDsWcUWZczDTeAJLHpuc/ts"),
            Channel(id: "2044537595", name: "beIN Sport 2 HD (Backup)", displayName: "beIN Sport 2 (Backup)", group: "القنوات الرياضية", logo: "beinSports_02_logo", path: nil),
            Channel(id: "2604364616", name: "beIN Sports 3 HD", displayName: "beIN Sports 3 HD", group: "القنوات الرياضية", logo: "beinSports_03_logo", path: "PhEJBHxb2ZwxlnzGwrQezM70wDN5icnfexvAbU_umEA/ts"),
            Channel(id: "2322261582", name: "beIN Sports 3 HD (Backup)", displayName: "beIN Sports 3 (Backup)", group: "القنوات الرياضية", logo: "beinSports_03_logo", path: nil),
            Channel(id: "1617035157", name: "beIN Sports 4 HD", displayName: "beIN Sports 4 HD", group: "القنوات الرياضية", logo: "beinSports_04_logo", path: "PhEJBHxb2ZwxlnzGwrQezB-xTIikYEK3a87MDi92A7Q/ts"),
            Channel(id: "3361859431", name: "beIN Sports 4 HD (Backup)", displayName: "beIN Sports 4 (Backup)", group: "القنوات الرياضية", logo: "beinSports_04_logo", path: nil),
            Channel(id: "2062676246", name: "AD Sport 1 HD", displayName: "AD Sport 1 HD", group: "القنوات الرياضية", logo: "AbuDhabi_Sports_1_Premium_logo", path: "PhEJBHxb2ZwxlnzGwrQezOKKR8VjTDlGKj30HA_kKrQ/ts"),
            Channel(id: "3992604526", name: "AD Sport 1 HD (Backup)", displayName: "AD Sport 1 (Backup)", group: "القنوات الرياضية", logo: "AbuDhabi_Sports_1_Premium_logo", path: "PhEJBHxb2ZwxlnzGwrQezOKKR8VjTDlGKj30HA_kKrQ/ts"),
            Channel(id: "4101961461", name: "AD Sport 2 HD", displayName: "AD Sport 2 HD", group: "القنوات الرياضية", logo: "AbuDhabi_Sports_2_Premium_logo", path: "PhEJBHxb2ZwxlnzGwrQezJogAbPUH6Yxn-RS34WvNaU/ts"),
            Channel(id: "276950299", name: "SSC 1 HD", displayName: "SSC 1 HD", group: "القنوات الرياضية", logo: "SSC_Sports-1", path: "PhEJBHxb2ZwxlnzGwrQezPT9THvcPmXTkhsmPSjrwSI/ts"),
            Channel(id: "1461819339", name: "SSC 2 HD", displayName: "SSC 2 HD", group: "القنوات الرياضية", logo: "SSC_Sports-2", path: "PhEJBHxb2ZwxlnzGwrQezDyZJsWua-zbzOgsyclk0kM/ts"),
            // القنوات الإخبارية
            Channel(id: "4237397671", name: "Al-Jazeera", displayName: "الجزيرة", group: "القنوات الإخبارية", logo: "al-jazeera-logo", path: nil),
            Channel(id: "2950207139", name: "Al-Jazeera-Mubasher", displayName: "الجزيرة مباشر", group: "القنوات الإخبارية", logo: "aljazera_mobasher", path: nil),
            Channel(id: "3208303251", name: "Al-Arabiya", displayName: "العربية", group: "القنوات الإخبارية", logo: "Al-Arabiya_logo", path: nil),
            Channel(id: "3948955561", name: "Al-Arabiya-Al-Hadath", displayName: "العربية الحدث", group: "القنوات الإخبارية", logo: "Al-Arabiya_ALHADAT", path: nil),
            Channel(id: "2048501234", name: "Sky News Arabia", displayName: "سكاي نيوز عربية", group: "القنوات الإخبارية", logo: "sky_news_arabia", path: nil),
            // القنوات الوثائقية
            Channel(id: "2678826992", name: "Al-Jazeera-Documentary", displayName: "الجزيرة الوثائقية", group: "القنوات الوثائقية", logo: "AL-jazera-decomontry", path: nil),
            Channel(id: "3203319196", name: "National-Geographic", displayName: "ناشيونال جيوغرافيك", group: "القنوات الوثائقية", logo: "National_Geographic-Logo.wine", path: nil),
            Channel(id: "1938155815", name: "DW", displayName: "DW", group: "القنوات الوثائقية", logo: "DW_(TV)_Logo_2012", path: nil),
            Channel(id: "2876543210", name: "Nat Geo Wild", displayName: "ناشيونال جيوغرافيك وايلد", group: "القنوات الوثائقية", logo: "nat_geo_wild", path: nil),
            // قنوات الأفلام
            Channel(id: "2776956416", name: "BeIN-Movies-2-HD", displayName: "BeIN Movies 2 HD", group: "قنوات الأفلام", logo: "MoviesHD2", path: nil),
            Channel(id: "2933030661", name: "BeIN-Fox-Movies-Family-HD", displayName: "BeIN Fox Movies Family HD", group: "قنوات الأفلام", logo: "Fox_Family_Movies_logo", path: nil),
            Channel(id: "3669198707", name: "MBC-2", displayName: "MBC 2", group: "قنوات الأفلام", logo: "MBC2_Logo", path: nil),
            Channel(id: "3272882914", name: "MBC-Action", displayName: "MBC Action", group: "قنوات الأفلام", logo: "MBC_Action_Logo", path: nil),
            Channel(id: "1987654321", name: "Netflix", displayName: "نتفليكس", group: "قنوات الأفلام", logo: "netflix_logo", path: nil),
            // قنوات الكرتون
            Channel(id: "592733992", name: "Spacetoon", displayName: "سبيستون", group: "قنوات الكرتون", logo: "Spacetoon", path: nil),
            Channel(id: "4089718739", name: "MBC-3", displayName: "MBC 3", group: "قنوات الكرتون", logo: "MBC_3_Transparent_Background_Logo", path: nil),
            Channel(id: "1234567890", name: "Cartoon Network", displayName: "كرتون نتورك", group: "قنوات الكرتون", logo: "cartoon_network", path: nil)
        ]
        _linkManager = StateObject(wrappedValue: ChannelLinkManager(channels: initialChannels))
    }
    
    let groupIcons: [String: String] = [
        "القنوات الرياضية": "Spot",
        "القنوات الإخبارية": "news",
        "القنوات الوثائقية": "Decomontry",
        "قنوات الأفلام": "Movies",
        "قنوات الكرتون": "Cartoon"
    ]
    
    var groupedChannels: [String: [Channel]] {
        Dictionary(grouping: linkManager.channels, by: { $0.group })
    }
    
    var favoriteChannels: [Channel] {
        linkManager.channels.filter { $0.isFavorite }
    }
    
    var body: some View {
        GeometryReader { geometry in
            ZStack {
                Image("background")
                    .resizable()
                    .scaledToFill()
                    .frame(width: geometry.size.width, height: geometry.size.height)
                    .clipped()
                    .edgesIgnoringSafeArea(.all)
                
                VStack(spacing: 0) {
                    Spacer(minLength: 50)
                    
                    VStack {
                        Image("loko")
                            .resizable()
                            .scaledToFit()
                            .frame(width: 120, height: 120)
                            .clipShape(RoundedRectangle(cornerRadius: 20))
                            .shadow(color: .black.opacity(0.3), radius: 15, x: 0, y: 10)
                            .overlay(
                                RoundedRectangle(cornerRadius: 20)
                                    .stroke(
                                        LinearGradient(
                                            gradient: Gradient(colors: [Color(hex: "00b4db"), Color(hex: "ff6f61")]),
                                            startPoint: .topLeading,
                                            endPoint: .bottomTrailing
                                        ),
                                        lineWidth: 2
                                    )
                            )
                    }
                    .padding(.bottom, 15)
                    
                    ScrollView {
                        switch currentTab {
                        case .home:
                            HomeContent(geometry: geometry)
                        case .watch:
                            WatchContent(
                                statusText: $statusText,
                                selectedGroup: $selectedGroup,
                                groupedChannels: groupedChannels,
                                favoriteChannels: favoriteChannels,
                                groupIcons: groupIcons,
                                showGroupScreen: $showGroupScreen,
                                playChannel: { channel in
                                    selectedChannel = channel
                                    withAnimation(.easeInOut) {
                                        showGroupScreen = false
                                        showPlayerScreen = true
                                    }
                                }
                            )
                        case .schedule:
                            ScheduleView()
                        case .about:
                            AboutContent()
                        }
                    }
                    .frame(maxWidth: .infinity)
                    .padding(.horizontal, geometry.safeAreaInsets.leading + 15)
                    
                    HStack(spacing: 0) {
                        TabButton(tab: .home, currentTab: $currentTab, icon: "house.fill", title: "الرئيسية")
                        TabButton(tab: .watch, currentTab: $currentTab, icon: "play.rectangle.fill", title: "العرض")
                        TabButton(tab: .schedule, currentTab: $currentTab, icon: "calendar", title: "الجدول")
                        TabButton(tab: .about, currentTab: $currentTab, icon: "info.circle.fill", title: "حول")
                    }
                    .frame(height: 70)
                    .background(
                        LinearGradient(
                            gradient: Gradient(colors: [Color.white.opacity(0.95), Color(hex: "f5f7fa").opacity(0.95)]),
                            startPoint: .top,
                            endPoint: .bottom
                        )
                    )
                    .clipShape(RoundedCorner(radius: 20, corners: [.topLeft, .topRight]))
                    .shadow(color: .black.opacity(0.1), radius: 10, x: 0, y: -5)
                    .padding(.horizontal, geometry.safeAreaInsets.leading)
                    .padding(.bottom, geometry.safeAreaInsets.bottom)
                }
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .background(Color(hex: "f5f7fa").opacity(0.9))
                
                if showGroupScreen, let group = selectedGroup {
                    GroupChannelsScreen(
                        group: group,
                        channels: groupedChannels[group] ?? [],
                        groupIcon: groupIcons[group] ?? "",
                        playChannel: { channel in
                            selectedChannel = channel
                            withAnimation(.easeInOut) {
                                showGroupScreen = false
                                showPlayerScreen = true
                            }
                        },
                        showGroupScreen: $showGroupScreen,
                        showPlayerScreen: $showPlayerScreen
                    )
                    .transition(.scale.combined(with: .opacity))
                }
                
                if showPlayerScreen, let channel = selectedChannel {
                    PlayerScreen(
                        channel: channel,
                        showPlayerScreen: $showPlayerScreen,
                        showGroupScreen: $showGroupScreen
                    )
                    .transition(.scale.combined(with: .opacity))
                    .zIndex(1)
                }
            }
        }
        .ignoresSafeArea(.keyboard)
        .environment(\.layoutDirection, .rightToLeft)
        .environmentObject(linkManager)
        .onAppear {
            linkManager.loadFavorites()
        }
    }
}

// شاشة قنوات المجموعة
struct GroupChannelsScreen: View {
    let group: String
    let channels: [Channel]
    let groupIcon: String
    let playChannel: (Channel) -> Void
    @Binding var showGroupScreen: Bool
    @Binding var showPlayerScreen: Bool
    @EnvironmentObject var linkManager: ChannelLinkManager
    
    var regularChannels: [Channel] {
        channels.filter { !$0.displayName.contains("Backup") }
    }
    
    var backupChannels: [Channel] {
        channels.filter { $0.displayName.contains("Backup") }
    }
    
    var body: some View {
        GeometryReader { geometry in
            ZStack {
                AsyncImage(url: URL(string: group == "القنوات الرياضية" ? "https://example.com/sports-bg.jpg" : "https://example.com/news-bg.jpg")) { image in
                    image.resizable().scaledToFill()
                } placeholder: { Color(hex: "f8fafc") }
                .edgesIgnoringSafeArea(.all)
                
                VStack(spacing: 20) {
                    VStack(spacing: 16) {
                        HStack(spacing: 15) {
                            Image(groupIcon)
                                .resizable()
                                .scaledToFit()
                                .frame(width: 80, height: 80)
                                .clipShape(Circle())
                                .overlay(Circle().stroke(Color(hex: "00b4db"), lineWidth: 2))
                                .shadow(radius: 5)
                            
                            Text(group)
                                .font(.custom("Questv1-Bold", size: 28))
                                .foregroundColor(.black)
                                .shadow(color: .black.opacity(0.2), radius: 2, x: 0, y: 1)
                            
                            Spacer()
                        }
                        Rectangle()
                            .fill(
                                LinearGradient(
                                    gradient: Gradient(colors: [Color(hex: "00b4db"), Color(hex: "ff6f61")]),
                                    startPoint: .leading,
                                    endPoint: .trailing
                                )
                            )
                            .frame(width: 96, height: 4)
                            .clipShape(RoundedRectangle(cornerRadius: 999))
                    }
                    .padding(.top, geometry.safeAreaInsets.top + 20)
                    .padding(.horizontal, 20)
                    
                    ScrollView {
                        VStack(spacing: 20) {
                            if group == "القنوات الرياضية" {
                                // القنوات الرئيسية
                                VStack(spacing: 12) {
                                    Text("القنوات الرئيسية")
                                        .font(.custom("Questv1-Bold", size: 22))
                                        .foregroundColor(.black)
                                        .padding(.vertical, 6)
                                        .padding(.horizontal, 16)
                                        .background(
                                            LinearGradient(
                                                gradient: Gradient(colors: [Color(hex: "e0f7ff"), Color(hex: "ffe6e6")]),
                                                startPoint: .leading,
                                                endPoint: .trailing
                                            )
                                        )
                                        .clipShape(RoundedRectangle(cornerRadius: 999))
                                    
                                    LazyVGrid(columns: [
                                        GridItem(.flexible(), spacing: 16),
                                        GridItem(.flexible(), spacing: 16)
                                    ], spacing: 16) {
                                        ForEach(regularChannels) { channel in
                                            ChannelCard(channel: channel, onTap: { playChannel(channel) })
                                        }
                                    }
                                }
                                
                                // القنوات الاحتياطية
                                VStack(spacing: 12) {
                                    Text("القنوات الاحتياطية")
                                        .font(.custom("Questv1-Bold", size: 22))
                                        .foregroundColor(.black)
                                        .padding(.vertical, 6)
                                        .padding(.horizontal, 16)
                                        .background(
                                            LinearGradient(
                                                gradient: Gradient(colors: [Color(hex: "e0f7ff"), Color(hex: "ffe6e6")]),
                                                startPoint: .leading,
                                                endPoint: .trailing
                                            )
                                        )
                                        .clipShape(RoundedRectangle(cornerRadius: 999))
                                    
                                    LazyVGrid(columns: [
                                        GridItem(.flexible(), spacing: 16),
                                        GridItem(.flexible(), spacing: 16)
                                    ], spacing: 16) {
                                        ForEach(backupChannels) { channel in
                                            ChannelCard(channel: channel, onTap: { playChannel(channel) })
                                        }
                                    }
                                }
                            } else {
                                LazyVGrid(columns: [
                                    GridItem(.flexible(), spacing: 16),
                                    GridItem(.flexible(), spacing: 16)
                                ], spacing: 16) {
                                    ForEach(channels) { channel in
                                        ChannelCard(channel: channel, onTap: { playChannel(channel) })
                                    }
                                }
                            }
                        }
                        .padding(.horizontal, 20)
                    }
                    
                    Button(action: {
                        withAnimation(.easeInOut(duration: 0.5)) {
                            showGroupScreen = false
                        }
                    }) {
                        Text(LocalizedStringKey("back"))
                            .font(.custom("Questv1-Bold", size: 18))
                            .foregroundColor(.white)
                            .padding(.vertical, 12)
                            .frame(maxWidth: .infinity)
                            .background(
                                LinearGradient(
                                    gradient: Gradient(colors: [Color(hex: "00b4db"), Color(hex: "ff6f61")]),
                                    startPoint: .leading,
                                    endPoint: .trailing
                                )
                            )
                            .cornerRadius(12)
                            .shadow(color: .black.opacity(0.2), radius: 5, x: 0, y: 2)
                    }
                    .padding(.horizontal, 20)
                    .padding(.bottom, 20)
                    .accessibilityLabel("العودة إلى الشاشة السابقة")
                }
                .background(Color.white.opacity(0.95))
                .clipShape(RoundedRectangle(cornerRadius: 20))
                .shadow(color: .black.opacity(0.1), radius: 10, x: 0, y: 5)
            }
        }
        .environment(\.layoutDirection, .rightToLeft)
    }
}

// محتوى شاشة العرض
struct WatchContent: View {
    @Binding var statusText: String
    @Binding var selectedGroup: String?
    let groupedChannels: [String: [Channel]]
    let favoriteChannels: [Channel]
    let groupIcons: [String: String]
    @Binding var showGroupScreen: Bool
    let playChannel: (Channel) -> Void
    
    var sortedGroups: [String] {
        let sportsGroup = "القنوات الرياضية"
        var groups = groupedChannels.keys.sorted()
        if let index = groups.firstIndex(of: sportsGroup) {
            groups.remove(at: index)
            groups.insert(sportsGroup, at: 0)
        }
        return groups
    }
    
    var body: some View {
        ScrollView {
            VStack(spacing: 40) {
                VStack(spacing: 16) {
                    Text(statusText)
                        .font(.custom("Questv1-Bold", size: 28))
                        .foregroundColor(.black)
                        .shadow(color: .black.opacity(0.2), radius: 2, x: 0, y: 1)
                        .multilineTextAlignment(.center)
                    
                    Rectangle()
                        .fill(
                            LinearGradient(
                                gradient: Gradient(colors: [Color(hex: "00b4db"), Color(hex: "ff6f61")]),
                                startPoint: .leading,
                                endPoint: .trailing
                            )
                        )
                        .frame(width: 120, height: 4)
                        .clipShape(RoundedRectangle(cornerRadius: 999))
                }
                .padding(.top, 20)
                
                if !favoriteChannels.isEmpty {
                    VStack(spacing: 12) {
                        Text("المفضلة")
                            .font(.custom("Questv1-Bold", size: 24))
                            .foregroundColor(.black)
                        LazyVGrid(columns: [
                            GridItem(.flexible(), spacing: 16),
                            GridItem(.flexible(), spacing: 16)
                        ], spacing: 16) {
                            ForEach(favoriteChannels) { channel in
                                ChannelCard(channel: channel, onTap: { playChannel(channel) })
                            }
                        }
                    }
                    .padding(.horizontal, 20)
                    .padding(.vertical, 20)
                    .background(Color.white.opacity(0.95))
                    .clipShape(RoundedRectangle(cornerRadius: 20))
                }
                
                ForEach(sortedGroups, id: \.self) { group in
                    GroupSection(
                        title: group,
                        groups: [group],
                        groupIcons: groupIcons,
                        onTap: { selectedGroup in
                            withAnimation(.easeInOut) {
                                self.selectedGroup = selectedGroup
                                showGroupScreen = true
                            }
                        }
                    )
                }
                
                VStack(spacing: 16) {
                    AsyncImage(url: URL(string: "https://png.pngtree.com/png-clipart/20211024/original/pngtree-coming-soon-png-image_6863544.png")) { image in
                        image
                            .resizable()
                            .scaledToFit()
                    } placeholder: {
                        ProgressView()
                            .tint(.black)
                    }
                    .frame(width: 120, height: 120)
                    .clipShape(Circle())
                    .overlay(Circle().stroke(Color(hex: "00b4db"), lineWidth: 2))
                    .shadow(color: .black.opacity(0.2), radius: 10, x: 0, y: 5)
                    
                    Text("المزيد من القنوات قادم قريبًا!")
                        .font(.custom("Questv1-Bold", size: 24))
                        .foregroundColor(.black)
                        .shadow(color: .black.opacity(0.2), radius: 2, x: 0, y: 1)
                    
                    Text("استعد لتجربة بث مذهلة مع قنوات جديدة ستضيف الحماس والتشويق إلى يومك!")
                        .font(.custom("Questv1-Bold", size: 16))
                        .foregroundColor(.black.opacity(0.8))
                        .multilineTextAlignment(.center)
                        .lineSpacing(4)
                }
                .padding(.vertical, 30)
                .padding(.horizontal, 20)
                .background(Color.white.opacity(0.95))
                .clipShape(RoundedRectangle(cornerRadius: 20))
                .shadow(color: .black.opacity(0.1), radius: 8, x: 0, y: 4)
            }
            .padding(.vertical, 40)
        }
        .background(Color(hex: "f8fafc").opacity(0.9))
        .clipShape(RoundedRectangle(cornerRadius: 20))
    }
}

// قسم المجموعة
struct GroupSection: View {
    let title: String
    let groups: [String]
    let groupIcons: [String: String]
    let onTap: (String) -> Void
    
    var body: some View {
        VStack(spacing: 12) {
            VStack(spacing: 8) {
                Text(title)
                    .font(.custom("Questv1-Bold", size: 24))
                    .foregroundColor(.black)
                    .shadow(color: .black.opacity(0.2), radius: 2, x: 0, y: 1)
                
                Rectangle()
                    .fill(
                        LinearGradient(
                            gradient: Gradient(colors: [Color(hex: "00b4db"), Color(hex: "ff6f61")]),
                            startPoint: .leading,
                            endPoint: .trailing
                        )
                    )
                    .frame(width: 96, height: 4)
                    .clipShape(RoundedRectangle(cornerRadius: 999))
            }
            
            LazyVGrid(columns: [
                GridItem(.flexible(), spacing: 16),
                GridItem(.flexible(), spacing: 16)
            ], spacing: 16) {
                ForEach(groups, id: \.self) { group in
                    GroupIconCard(
                        group: group,
                        icon: groupIcons[group] ?? "",
                        onTap: { onTap(group) }
                    )
                }
            }
        }
        .padding(.horizontal, 20)
        .padding(.vertical, 20)
        .background(Color.white.opacity(0.95))
        .clipShape(RoundedRectangle(cornerRadius: 20))
        .shadow(color: .black.opacity(0.1), radius: 5, x: 0, y: 2)
    }
}

// بطاقة أيقونة المجموعة
struct GroupIconCard: View {
    let group: String
    let icon: String
    let onTap: () -> Void
    
    @State private var isHovered = false
    
    var body: some View {
        Button(action: onTap) {
            VStack(spacing: 12) {
                Image(icon)
                    .resizable()
                    .scaledToFit()
                    .frame(width: 80, height: 80)
                    .clipShape(Circle())
                    .overlay(Circle().stroke(Color(hex: "00b4db"), lineWidth: 2))
                    .shadow(radius: 5)
                    .scaleEffect(isHovered ? 1.05 : 1.0)
                
                Text(group)
                    .font(.custom("Questv1-Bold", size: 18))
                    .foregroundColor(.black)
                    .shadow(color: .black.opacity(0.2), radius: 2, x: 0, y: 1)
            }
            .padding(16)
            .background(Color.white.opacity(0.95))
            .clipShape(RoundedRectangle(cornerRadius: 16))
            .shadow(color: .black.opacity(0.05), radius: 4, x: 0, y: 2)
        }
        .scaleEffect(isHovered ? 0.98 : 1.0)
        .animation(.spring(response: 0.4, dampingFraction: 0.6), value: isHovered)
        .onHover { hovering in
            isHovered = hovering
        }
        .accessibilityLabel("فتح مجموعة \(group)")
    }
}

// محتوى الشاشة الرئيسية
struct HomeContent: View {
    let geometry: GeometryProxy
    
    let leagues: [League] = [
        League(id: "1", name: "الدوري الإنجليزي", description: "أقوى دوري في العالم يضم أندية مثل مانشستر سيتي وليفربول.", highlight: "أكثر نادٍ فاز باللقب: مانشستر يونايتد (13 مرة)", logo: "1"),
        League(id: "2", name: "الدوري الإسباني", description: "موطن الكلاسيكو بين برشلونة وريال مدريد.", highlight: "أكثر نادٍ فاز باللقب: ريال مدريد (35 مرة)", logo: "LaLiga-Logo"),
        League(id: "3", name: "الدوري الإيطالي", description: "دوري تكتيكي يشتهر بأندية مثل يوفنتوس وميلان.", highlight: "أكثر نادٍ فاز باللقب: يوفنتوس (36 مرة)", logo: "Serie_A_logo"),
        League(id: "4", name: "الدوري الألماني", description: "دوري يجمع بين القوة والشغف مع أندية مثل بايرن ميونخ.", highlight: "أكثر نادٍ فاز باللقب: بايرن ميونخ (32 مرة)", logo: "Logo_Bundesliga"),
        League(id: "5", name: "الدوري الفرنسي", description: "يضم نجوم العالم في باريس سان جيرمان ومارسيليا.", highlight: "أكثر نادٍ فاز باللقب: باريس سان جيرمان (11 مرة)", logo: "Ligue_1")
    ]
    
    var body: some View {
        VStack(spacing: 40) {
            VStack(spacing: 20) {
                Text("تجربة بث فريدة من نوعها")
                    .font(.custom("Questv1-Bold", size: 16))
                    .foregroundColor(.black)
                    .padding(.horizontal, 16)
                    .padding(.vertical, 8)
                    .background(Color.white.opacity(0.2))
                    .clipShape(RoundedRectangle(cornerRadius: 999))
                    .shadow(color: .black.opacity(0.2), radius: 5, x: 0, y: 2)
                
                Text("انطلق في عالم الترفيه مع\niDEB Sport 4K")
                    .font(.custom("Questv1-Bold", size: 32))
                    .foregroundColor(.black)
                    .shadow(color: .black.opacity(0.2), radius: 2, x: 0, y: 1)
                    .multilineTextAlignment(.center)
                
                Text("استمتع ببث مباشر بجودة فائقة الوضوح")
                    .font(.custom("Questv1-Bold", size: 18))
                    .foregroundColor(.black.opacity(0.8))
                    .multilineTextAlignment(.center)
            }
            .padding(.vertical, 40)
            
            VStack(spacing: 24) {
                VStack(spacing: 12) {
                    Text("مجموعة متنوعة من الدوريات")
                        .font(.custom("Questv1-Bold", size: 16))
                        .foregroundColor(.black)
                        .padding(.horizontal, 16)
                        .padding(.vertical, 6)
                        .background(
                            LinearGradient(
                                gradient: Gradient(colors: [Color(hex: "e0f7ff"), Color(hex: "ffe6e6")]),
                                startPoint: .leading,
                                endPoint: .trailing
                            )
                        )
                        .clipShape(RoundedRectangle(cornerRadius: 999))
                    
                    Text("اكتشف وتابع الدوري المفضل لديك")
                        .font(.custom("Questv1-Bold", size: 28))
                        .foregroundColor(.black)
                        .shadow(color: .black.opacity(0.2), radius: 2, x: 0, y: 1)
                    
                    Rectangle()
                        .fill(
                            LinearGradient(
                                gradient: Gradient(colors: [Color(hex: "00b4db"), Color(hex: "ff6f61")]),
                                startPoint: .leading,
                                endPoint: .trailing
                            )
                        )
                        .frame(width: 96, height: 4)
                        .clipShape(RoundedRectangle(cornerRadius: 999))
                }
                
                LazyVGrid(columns: [
                    GridItem(.flexible(), spacing: 16),
                    GridItem(.flexible(), spacing: 16)
                ], spacing: 16) {
                    ForEach(leagues) { league in
                        LeagueCard(league: league)
                    }
                }
            }
            .padding(.vertical, 40)
            .background(Color(hex: "f8fafc").opacity(0.95))
            .clipShape(RoundedRectangle(cornerRadius: 20))
            .shadow(color: .black.opacity(0.1), radius: 8, x: 0, y: 4)
        }
        .padding(.top, 20)
    }
}

// شاشة الجدول
struct ScheduleView: View {
    let matches: [Match] = [
        Match(id: "1", teams: "مانشستر سيتي vs ليفربول", date: "2025-03-24 18:00", league: "الدوري الإنجليزي"),
        Match(id: "2", teams: "برشلونة vs ريال مدريد", date: "2025-03-25 20:00", league: "الدوري الإسباني")
    ]
    
    var body: some View {
        VStack(spacing: 20) {
            Text("جدول المباريات القادمة")
                .font(.custom("Questv1-Bold", size: 28))
                .foregroundColor(.black)
                .shadow(color: .black.opacity(0.2), radius: 2, x: 0, y: 1)
            
            ScrollView {
                LazyVStack(spacing: 16) {
                    ForEach(matches) { match in
                        MatchCard(match: match)
                    }
                }
                .padding(.horizontal, 20)
            }
        }
        .padding(.vertical, 40)
        .background(Color(hex: "f8fafc").opacity(0.95))
        .clipShape(RoundedRectangle(cornerRadius: 20))
    }
}

// هيكل المباراة
struct Match: Identifiable {
    let id: String
    let teams: String
    let date: String
    let league: String
}

// بطاقة المباراة
struct MatchCard: View {
    let match: Match
    @State private var isHovered = false
    
    var body: some View {
        VStack(spacing: 12) {
            Text(match.teams)
                .font(.custom("Questv1-Bold", size: 20))
                .foregroundColor(.black)
            Text(match.date)
                .font(.custom("Questv1-Bold", size: 16))
                .foregroundColor(.gray)
            Text(match.league)
                .font(.custom("Questv1-Bold", size: 14))
                .foregroundColor(.black.opacity(0.8))
        }
        .padding(20)
        .background(Color.white.opacity(0.95))
        .clipShape(RoundedRectangle(cornerRadius: 16))
        .shadow(color: .black.opacity(0.05), radius: 4, x: 0, y: 2)
        .scaleEffect(isHovered ? 0.98 : 1.0)
        .animation(.spring(response: 0.4, dampingFraction: 0.6), value: isHovered)
        .onHover { hovering in
            isHovered = hovering
        }
    }
}

// محتوى صفحة "حول"
struct AboutContent: View {
    var body: some View {
        VStack(spacing: 32) {
            VStack(spacing: 16) {
                Text("ما الذي يجعل iDEB Sport Premium 4K الخيار الأمثل؟")
                    .font(.custom("Questv1-Bold", size: 28))
                    .foregroundColor(.black)
                    .shadow(color: .black.opacity(0.2), radius: 2, x: 0, y: 1)
                    .multilineTextAlignment(.center)
                
                Rectangle()
                    .fill(
                        LinearGradient(
                            gradient: Gradient(colors: [Color(hex: "00b4db"), Color(hex: "ff6f61")]),
                            startPoint: .leading,
                            endPoint: .trailing
                        )
                    )
                    .frame(width: 96, height: 4)
                    .clipShape(RoundedRectangle(cornerRadius: 999))
            }
            
            LazyVGrid(columns: [
                GridItem(.flexible(), spacing: 16),
                GridItem(.flexible(), spacing: 16)
            ], spacing: 16) {
                WhyUsItem(icon: "tv.fill", title: "جودة فائقة الوضوح", description: "عش تجربة بصرية استثنائية مع جودة 4K.")
                WhyUsItem(icon: "server.rack", title: "أداء موثوق", description: "بث سلس دون تقطيع.")
            }
        }
        .padding(.vertical, 40)
        .background(Color(hex: "f8fafc").opacity(0.95))
        .clipShape(RoundedRectangle(cornerRadius: 20))
        .shadow(color: .black.opacity(0.1), radius: 8, x: 0, y: 4)
    }
}

// عنصر "لماذا نحن"
struct WhyUsItem: View {
    let icon: String
    let title: String
    let description: String
    
    @State private var isHovered = false
    
    var body: some View {
        VStack(spacing: 16) {
            Image(systemName: icon)
                .font(.system(size: 40))
                .foregroundColor(Color(hex: "00b4db"))
                .scaleEffect(isHovered ? 1.05 : 1.0)
            
            Text(title)
                .font(.custom("Questv1-Bold", size: 20))
                .foregroundColor(.black)
                .shadow(color: .black.opacity(0.2), radius: 2, x: 0, y: 1)
            
            Text(description)
                .font(.custom("Questv1-Bold", size: 16))
                .foregroundColor(.black.opacity(0.8))
                .multilineTextAlignment(.center)
                .lineSpacing(4)
        }
        .padding(24)
        .background(Color.white.opacity(0.95))
        .clipShape(RoundedRectangle(cornerRadius: 16))
        .shadow(color: .black.opacity(0.05), radius: 4, x: 0, y: 2)
        .scaleEffect(isHovered ? 0.98 : 1.0)
        .animation(.spring(response: 0.4, dampingFraction: 0.6), value: isHovered)
        .onHover { hovering in
            isHovered = hovering
        }
    }
}

// زر التبويب
struct TabButton: View {
    let tab: Tab
    @Binding var currentTab: Tab
    let icon: String
    let title: String
    
    @State private var isHovered = false
    
    var body: some View {
        Button {
            withAnimation(.easeInOut) {
                currentTab = tab
            }
        } label: {
            VStack(spacing: 6) {
                Image(systemName: icon)
                    .font(.system(size: 22))
                    .scaleEffect(isHovered || currentTab == tab ? 1.1 : 1.0)
                Text(title)
                    .font(.custom("Questv1-Bold", size: 14))
                    .foregroundColor(currentTab == tab ? .black : .gray)
                    .shadow(color: .black.opacity(0.2), radius: 2, x: 0, y: 1)
            }
            .frame(maxWidth: .infinity)
            .padding(.vertical, 10)
        }
        .scaleEffect(isHovered ? 0.95 : 1.0)
        .animation(.spring(response: 0.3, dampingFraction: 0.6), value: isHovered)
        .onHover { hovering in
            isHovered = hovering
        }
        .accessibilityLabel(title)
    }
}

enum Tab {
    case home, watch, schedule, about
}

// بطاقة الدوري
struct LeagueCard: View {
    let league: League
    @State private var isHovered = false
    
    var body: some View {
        VStack(spacing: 16) {
            Image(league.logo)
                .resizable()
                .scaledToFit()
                .frame(width: 100, height: 100)
                .clipShape(Circle())
                .shadow(color: .black.opacity(0.1), radius: 5, x: 0, y: 2)
                .scaleEffect(isHovered ? 1.05 : 1.0)
            
            Text(league.name)
                .font(.custom("Questv1-Bold", size: 18))
                .foregroundColor(.black)
                .shadow(color: .black.opacity(0.2), radius: 2, x: 0, y: 1)
            
            Text(league.description)
                .font(.custom("Questv1-Bold", size: 14))
                .foregroundColor(.black.opacity(0.8))
                .multilineTextAlignment(.center)
                .lineSpacing(4)
            
            Text(league.highlight)
                .font(.custom("Questv1-Bold", size: 12))
                .foregroundColor(.gray)
                .multilineTextAlignment(.center)
        }
        .padding(20)
        .background(Color.white.opacity(0.95))
        .clipShape(RoundedRectangle(cornerRadius: 16))
        .shadow(color: .black.opacity(0.05), radius: 4, x: 0, y: 2)
        .scaleEffect(isHovered ? 0.98 : 1.0)
        .animation(.spring(response: 0.4, dampingFraction: 0.6), value: isHovered)
        .onHover { hovering in
            isHovered = hovering
        }
    }
}

// هيكل الدوري
struct League: Identifiable {
    let id: String
    let name: String
    let description: String
    let highlight: String
    let logo: String
}

// بطاقة القناة
struct ChannelCard: View {
    let channel: Channel
    let onTap: () -> Void
    @EnvironmentObject var linkManager: ChannelLinkManager
    @State private var isHovered = false
    
    var body: some View {
        Button(action: onTap) {
            VStack(spacing: 10) {
                Image(channel.logo)
                    .resizable()
                    .scaledToFit()
                    .frame(width: 80, height: 80)
                    .clipShape(Circle())
                    .overlay(Circle().stroke(Color(hex: "00b4db"), lineWidth: 1))
                    .shadow(color: isHovered ? Color.blue.opacity(0.7) : Color.clear, radius: 10)
                    .scaleEffect(isHovered ? 1.05 : 1.0)
                
                Text(channel.displayName)
                    .font(.custom("Questv1-Bold", size: 16))
                    .foregroundColor(.black)
                    .multilineTextAlignment(.center)
                    .shadow(color: .black.opacity(0.2), radius: 2, x: 0, y: 1)
                
                Button(action: {
                    linkManager.toggleFavorite(channelId: channel.id)
                }) {
                    Image(systemName: channel.isFavorite ? "heart.fill" : "heart")
                        .foregroundColor(channel.isFavorite ? .red : .gray)
                }
                .accessibilityLabel(channel.isFavorite ? "إزالة من المفضلة" : "إضافة إلى المفضلة")
            }
            .padding(12)
            .background(Color.white.opacity(0.95))
            .cornerRadius(15)
            .shadow(color: .black.opacity(0.05), radius: 4, x: 0, y: 2)
        }
        .scaleEffect(isHovered ? 0.98 : 1.0)
        .animation(.spring(response: 0.4, dampingFraction: 0.6), value: isHovered)
        .onHover { hovering in
            isHovered = hovering
        }
        .accessibilityLabel("تشغيل \(channel.displayName)")
    }
}

// تحويل اللون من Hex
extension Color {
    init(hex: String) {
        let hex = hex.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
        var int: UInt64 = 0
        Scanner(string: hex).scanHexInt64(&int)
        let a, r, g, b: UInt64
        switch hex.count {
        case 3: // RGB (12-bit)
            (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
        case 6: // RGB (24-bit)
            (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
        case 8: // ARGB (32-bit)
            (a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
        default:
            (a, r, g, b) = (255, 0, 0, 0)
        }
        self.init(.sRGB, red: Double(r) / 255, green: Double(g) / 255, blue: Double(b) / 255, opacity: Double(a) / 255)
    }
}

// شكل الزوايا الدائرية
struct RoundedCorner: Shape {
    var radius: CGFloat = .infinity
    var corners: UIRectCorner = .allCorners
    
    func path(in rect: CGRect) -> Path {
        let path = UIBezierPath(
            roundedRect: rect,
            byRoundingCorners: corners,
            cornerRadii: CGSize(width: radius, height: radius)
        )
        return Path(path.cgPath)
    }
}

// معالج إعادة التوجيه
class RedirectHandler: NSObject, URLSessionTaskDelegate {
    func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
        completionHandler(nil)
    }
}

// شاشة الترحيب
struct WelcomeScreen: View {
    @State private var animate = false
    @Binding var showWelcome: Bool
    
    var body: some View {
        ZStack {
            LinearGradient(
                gradient: Gradient(colors: [Color(hex: "1e3c72"), Color(hex: "ff6f61"), Color(hex: "00b4db")]),
                startPoint: .topLeading,
                endPoint: .bottomTrailing
            )
            .edgesIgnoringSafeArea(.all)
            
            VStack(spacing: 30) {
                Image("loko")
                    .resizable()
                    .scaledToFit()
                    .frame(width: 250, height: 250)
                    .clipShape(RoundedRectangle(cornerRadius: 40))
                    .shadow(color: .black.opacity(0.7), radius: 30, x: 0, y: 15)
                    .scaleEffect(animate ? 1.0 : 0.5)
                    .opacity(animate ? 1.0 : 0.0)
                    .animation(.spring(response: 0.8, dampingFraction: 0.6, blendDuration: 0.3).delay(0.2), value: animate)
                
                Text("iDEB Sports 4K")
                    .font(.custom("Questv1-Bold", size: 52))
                    .foregroundColor(.white)
                    .shadow(color: .black.opacity(0.6), radius: 8, x: 0, y: 4)
                    .opacity(animate ? 1.0 : 0.0)
                    .offset(y: animate ? 0 : 70)
                    .animation(.interpolatingSpring(stiffness: 100, damping: 15).delay(0.5), value: animate)
                
                Text("لا تفوت لحظة")
                    .font(.custom("Questv1-Bold", size: 28))
                    .foregroundColor(.white.opacity(0.9))
                    .shadow(color: .black.opacity(0.5), radius: 5, x: 0, y: 2)
                    .opacity(animate ? 1.0 : 0.0)
                    .offset(y: animate ? 0 : 50)
                    .animation(.interpolatingSpring(stiffness: 80, damping: 12).delay(0.8), value: animate)
            }
        }
        .onAppear {
            withAnimation {
                animate = true
            }
            DispatchQueue.main.asyncAfter(deadline: .now() + 4.5) {
                withAnimation(.easeInOut(duration: 1.2)) {
                    showWelcome = false
                }
            }
        }
    }
}

// العرض الرئيسي مع شاشة الترحيب
struct ContentView: View {
    @State private var showWelcome = true
    
    var body: some View {
        ZStack {
            MainView()
            if showWelcome {
                WelcomeScreen(showWelcome: $showWelcome)
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
            .previewDevice(PreviewDevice(rawValue: "iPhone 14 Pro Max"))
    }
}
